import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { getUrlParam, addUrlParam } from '@/utils/urlUtils';

const JpgPreview = () => {
  console.log('=== JpgPreview 组件开始渲染 ===');
  
  const location = useLocation();
  const [fileInfo, setFileInfo] = useState(null);
  const [processedFileUrl, setProcessedFileUrl] = useState('');
  const [scale, setScale] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [imageReady, setImageReady] = useState(false);

  console.log('当前路由位置:', location);
  console.log('路由状态数据:', location.state);

  useEffect(() => {
    console.log('JpgPreview useEffect 触发');
    console.log('location.state:', location.state);
    
    // 从路由状态中获取文件信息
    if (location.state && location.state.fileList && location.state.fileList.length > 0) {
      console.log('找到文件列表，设置第一个文件信息');
      console.log('文件列表:', location.state.fileList);
      console.log('选择的文件:', location.state.fileList[0]);
      setFileInfo(location.state.fileList[0]);
    } else {
      console.warn('未找到有效的文件信息');
      console.warn('location.state:', location.state);
    }
  }, [location.state]);

  // 预处理fileUrl，添加accessToken参数
  useEffect(() => {
    console.log('=== JpgPreview fileUrl预处理开始 ===');
    console.log('原始fileInfo:', fileInfo);
    
    if (!fileInfo || !fileInfo.fileUrl) {
      console.log('fileInfo或fileUrl为空，跳过预处理');
      setProcessedFileUrl('');
      setImageReady(false);
      return;
    }
    
    // 重置状态
    setImageReady(false);
    setLoading(true);
    setError(null);
    
    // 从页面URL中获取accessToken参数
    const accessToken = getUrlParam('accessToken');
    console.log('从页面URL获取的accessToken:', accessToken);
    
    let finalFileUrl = fileInfo.fileUrl;
    
    // 如果存在accessToken，则添加到fileUrl中
    if (accessToken) {
      console.log('检测到accessToken，开始拼接到fileUrl');
      finalFileUrl = addUrlParam(fileInfo.fileUrl, 'accessToken', accessToken);
      console.log('拼接accessToken后的fileUrl:', finalFileUrl);
    } else {
      console.log('未检测到accessToken，使用原始fileUrl');
    }
    
    setProcessedFileUrl(finalFileUrl);
    // 延迟一小段时间确保状态更新完成后再标记为准备就绪
    setTimeout(() => {
      setImageReady(true);
      console.log('图片URL准备就绪，可以开始加载');
    }, 100);
    
    console.log('=== JpgPreview fileUrl预处理完成 ===');
    console.log('最终处理后的fileUrl:', finalFileUrl);
  }, [fileInfo]);

  const handleImageLoad = () => {
    console.log('图片加载成功');
    setLoading(false);
    setError(null);
  };

  const handleImageError = () => {
    console.error('图片加载失败');
    console.error('失败的URL:', processedFileUrl);
    setLoading(false);
    setError('图片加载失败，请检查文件链接是否有效');
  };

  const retryLoad = () => {
    console.log('重新加载图片');
    setLoading(true);
    setError(null);
    setImageReady(false);
    
    // 重新触发图片加载
    setTimeout(() => {
      setImageReady(true);
    }, 100);
  };

  console.log('当前文件信息状态:', fileInfo);
  console.log('图片准备状态:', imageReady);
  console.log('处理后的URL:', processedFileUrl);

  if (!fileInfo) {
    console.log('渲染文件信息缺失页面');
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-96">
          <CardHeader>
            <CardTitle className="text-red-600">文件信息缺失</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600">
              无法获取图片文件信息，请重新访问预览链接。
            </p>
            <div className="mt-4 text-xs text-gray-400">
              <p>调试信息:</p>
              <p>location.state: {JSON.stringify(location.state)}</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-96">
          <CardHeader>
            <CardTitle className="text-red-600">加载失败</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600 mb-4">{error}</p>
            <Button onClick={retryLoad} className="w-full">
              重新加载
            </Button>
            <div className="mt-4 text-xs text-gray-400">
              <p>调试信息:</p>
              <p>原始URL: {fileInfo.fileUrl}</p>
              <p>处理后URL: {processedFileUrl}</p>
              <p>accessToken: {getUrlParam('accessToken') || '未找到'}</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  console.log('渲染JPG预览组件');

  return (
    <div className="min-h-screen flex items-center justify-center">
      {/* 图片内容区域 - 使用flex布局使图片居中 */}
      <div className="w-full flex items-center justify-center">
        {loading && (
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">正在加载图片...</p>
          </div>
        )}
        {imageReady && processedFileUrl && (
          <img
            key={processedFileUrl}
            src={processedFileUrl}
            alt={fileInfo.fileName || '预览图片'}
            className="mx-auto object-cover"
            style={{
              maxWidth: '100%',
              maxHeight: '100vh',
              height: 'auto',
              display: loading ? 'none' : 'block'
            }}
            onLoad={handleImageLoad}
            onError={handleImageError}
          />
        )}
      </div>
    </div>
  );
};

export default JpgPreview;
